package com.hs.shirodemo2.config;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.hs.shirodemo2.utils.JwtUtil;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionContext;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;


/**
 * @ClassName MySessionManager
 * @Description 自定义的SessionManager  用来传递token
 */
public class MySessionManager extends DefaultWebSessionManager {
    /**
     * 从请求中获取sessionId
     */
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String token = WebUtils.toHttp(request).getHeader("token");

        if (token ==null|| "".equals(token.trim())) {
            //按默认规则从cookie取sessionId
            return super.getSessionId(request, response);
        } else {
            DecodedJWT decodedJWT = JwtUtil.parseData(token);
            String id = decodedJWT.getId();

            //如果请求头中有 Authorization 则其值为sessionId
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "url");
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return id;
        }
    }

    @Override
    protected void onStart(Session session, SessionContext context) {
        super.onStart(session, context);
        if (!WebUtils.isHttp(context)) {
            System.out.println("No session ID cookie will be set.");
        } else {
            HttpServletRequest request = WebUtils.getHttpRequest(context);
            HttpServletResponse response = WebUtils.getHttpResponse(context);
            //将会话编号保存在resp的header的token中
            Serializable id = session.getId();
            String  token= JwtUtil.toToken("xj","java",id.toString(),null);
            // ! 让前端可以跨域访问token
            response.setHeader("Access-Control-Expose-Headers","token");
            response.setHeader("token",token);
            request.removeAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_IS_NEW, Boolean.TRUE);
        }

    }
}
